package cn.fanqinghong.ymcc.mq.consumer;

import cn.fanqinghong.ymcc.constants.MessageConstants;
import cn.fanqinghong.ymcc.domain.MessageEmail;
import cn.fanqinghong.ymcc.dto.EmailMessageDto;
import cn.fanqinghong.ymcc.dto.SmsMessageDto;
import cn.fanqinghong.ymcc.exception.GlobalException;
import cn.fanqinghong.ymcc.service.IMessageEmailService;
import cn.fanqinghong.ymcc.utils.MailUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * FAN
 * 2022/7/25  19:36
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = MessageConstants.EMAIL_CONSUMER_GROUP,
        topic = MessageConstants.EMAIL_TOPIC,
        selectorExpression = MessageConstants.EMAIL_TAGES
)
public class MessageEmailConsumer implements RocketMQListener<MessageExt> {


    @Autowired
    private IMessageEmailService messageEmailService;
    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        try {
            String jsonStr = new String(message.getBody(), CharsetUtil.UTF_8);
            //把接收到的消息转为MediaFile格式
            EmailMessageDto emailMessageDto = JSONObject.parseObject(jsonStr, EmailMessageDto.class);
            //保存数据到数据库
            SaveMessageEmail(emailMessageDto);

            //发送邮件 并且保存数据到数据库

            log.info("message"+emailMessageDto.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("邮件发送失败");
        }


    }

    private void SaveMessageEmail(EmailMessageDto emailMessageDto) {
        Date date = new Date();
        emailMessageDto.getDtos().forEach(user ->{
            MessageEmail messageEmail = new MessageEmail();
            messageEmail.setEmail(user.getEmali());
            messageEmail.setUserId(user.getId());
            BeanUtils.copyProperties(emailMessageDto,messageEmail);
            messageEmail.setSendTime(date);
            //保存数据
            messageEmailService.insert(messageEmail);
            //发送邮件
            //MailUtil.sendEasyMailPass(messageEmail);
        });
    }
}
